<template>
  <van-pull-refresh :disabled="onPullDownRefresh==null" v-model="isLoading" @refresh="onRefresh">
    <router-view></router-view>
  </van-pull-refresh>
</template>

<script>
import api from "@/api/api";
import { PullRefresh } from "vant";
export default {
  components: {
    "van-pull-refresh": PullRefresh
  },

  data() {
    return {
      isLoading: false,
      onPullDownRefresh: null,
      onReachBottom: null,
      scrollListener: null
    }
  },

  watch: {
    $route() {
      this.disablePullDownRefresh();
      this.disableReachBottom();
    }
  },

  mounted() {
    api.refreshObj = this;
    this.scrollListener = () => {
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
      let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
      if (scrollHeight - scrollTop - windowHeight == 0) {
        if (this.onReachBottom) {
          this.onReachBottom();
        }
      }
    };
  },

  destroyed() {
    this.disablePullDownRefresh();
    this.disableReachBottom();
    this.scrollListener = null;
    api.refreshObj = null;
  },

  methods: {
    enablePullDownRefresh(component) {
      if (component && typeof component.onPullDownRefresh == "function") {
        this.onPullDownRefresh = component.onPullDownRefresh;
      }
    },

    disablePullDownRefresh() {
      this.isLoading = false;
      this.onPullDownRefresh = null;
    },

    onRefresh() {
      if (this.onPullDownRefresh) {
        this.onPullDownRefresh();
      }
    },

    stopPullDownRefresh() {
      this.isLoading = false;
    },

    enableReachBottom(component) {
      if (component && typeof component.onReachBottom == "function") {
        this.onReachBottom = component.onReachBottom;
        window.addEventListener("scroll", this.scrollListener, false);
      }
    },

    disableReachBottom() {
      this.onReachBottom = null;
      window.removeEventListener("scroll", this.scrollListener, false);
    },
  }
}
</script>